import { BaseLoader } from './BaseLoader'

/**
 * @description JS 加载器
 * */
export class JsLoader extends BaseLoader {
  private static instance: JsLoader

  static getInstance(): JsLoader {
    if (!this.instance) this.instance = new JsLoader()
    return this.instance
  }

  isLoaded(url: string): boolean {
    return Array.from(document.scripts).some((script) => script.src.includes(url))
  }

  load(url: string): Promise<true> {
    if (this.isLoaded(url)) return Promise.resolve(true)
    return new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.defer = true // 异步
      script.onload = () => resolve(true)
      script.onerror = () => {
        reject(new Error(`JS 资源加载失败: ${url}`))
      }
      document.body.appendChild(script)
    })
  }
}

/**
 * @description CSS 加载器
 * */
export class CssLoader extends BaseLoader {
  private static instance: CssLoader

  static getInstance(): CssLoader {
    if (!this.instance) this.instance = new CssLoader()
    return this.instance
  }

  isLoaded(url: string): boolean {
    return Array.from(document.styleSheets).some((sheet) => !!sheet.href?.includes(url))
  }

  load(url: string): Promise<true> {
    if (this.isLoaded(url)) return Promise.resolve(true)
    return new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      link.onload = () => resolve(true)
      link.onerror = () => {
        reject(new Error(`CSS 资源加载失败: ${url}`))
      }
      document.head.appendChild(link)
    })
  }
}
